<template>
    <div class="album-catalog">
        <el-tabs v-model="tabIndex" type="card" editable @edit="editTab">
            <el-tab-pane v-for="(item, index) in tabsData" :key="index" :label="item.title" :name="item.inx">
                <div class="content">
                    <div :class="errorFlag && item.name === '' ? 'validate-input' : ''">
                        <el-input v-model.trim="item.name" placeholder="输入阶段/单元名称，40字符以内" maxlength="40"></el-input>
                        <!-- <p v-if="errorFlag && item.name === ''">阶段/单元名称不能为空</p> -->
                    </div>
                    <template>
                        <el-table v-if="item.relate_data.length > 0" :data="item.relate_data" tooltip-effect="dark" class="relate-table">
                            <el-table-column show-overflow-tooltip>
                                <template slot-scope="scope">
                                    <span style="margin-left: 10px;">{{ scope.row.name }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column width="60">
                                <template slot-scope="scope">
                                    <i class="el-icon-delete" @click="delresource(scope)"></i>
                                </template>
                            </el-table-column>
                        </el-table>
                    </template>
                </div>
            </el-tab-pane>
        </el-tabs>
        <el-row class="btns-row">
            <el-button type="primary" @click="connect('video')">关联视频</el-button>
            <!-- <el-button type="primary" @click="connect('test')">关联试卷</el-button> -->
            <el-button type="primary" @click="connect('resource')">关联资源</el-button>
            <uploader :options="uploadOptions" :autoStart="false" ref="uploaderRes" :file-status-text="statusText" @files-submitted="fileSubmitRes" @file-removed="fileRemovedRes" @file-success="fileSuccessRes" @file-error="fileFailRes" class="uploader">
                <uploader-unsupport></uploader-unsupport>
                <uploader-btn :directory="false" :single="true">
                    <el-button type="primary">本地上传</el-button>
                </uploader-btn>
            </uploader>
        </el-row>
        <connectTable title="选择视频" placeholder="视频名、用户名" ref="videoTable" :tab='tabIndex' v-model="videoChecked" :tableData="videoData" :column="videoColumn" :getData="searchVideo">
            <el-select v-model="videoType" placeholder="请选择" @change="searchVideo">
                <el-option label="全部" :value="-1"></el-option>
                <el-option label="公开课" :value="0"></el-option>
            </el-select>
        </connectTable>
        <!-- <connectTable title="选择试卷" placeholder="试卷名" ref="testTable" :tableData="testData" :column="testColumn" :getData="searchTest">
    </connectTable> -->
        <connectTable title="选择资源" placeholder="资源名、用户名" ref="resourceTable" v-model="resourceChecked" :tableData="resourceData" :column="resourceColumn" :getData="searchResource" :tab='tabIndex'>
            <el-select v-model="resourceType" placeholder="请选择" @change="searchResource">
                <template v-for="(item, index) of types">
                    <el-option v-if="index != 2" :key="index" :label="item" :value="index"></el-option>
                </template>
            </el-select>
        </connectTable>
    </div>
</template>
<script>
import connectTable from './album-connect-table';
export default {
    components: {
        connectTable
    },
    model: {
        prop: 'value'
    },
    props: {
        postData: Function
    },
    data() {
        return {
            // tabs
            tabIndex: '1',
            tabsData: [{
                title: '第1章',
                inx: '1',
                name: '',
                profile: '',
                relate_data: []
            }],
            // 关联视频
            videoVisible: false,
            videoType: '',
            keyword: '',
            videoData: {},
            videoColumn: [
                { prop: 'video_name', label: '视频名称', width: 215 },
                { prop: 'category', label: '视频分类', width: 160 },
                { prop: 'user_name', label: '用户名', width: '' },
                { prop: 'type_name', label: '视频信息', width: 80 },
                { prop: 'create_time', label: '上传时间', width: 140 }
            ],
            videoChecked: [],
            // 关联试卷
            // testVisible: false,
            // keyword: '',
            // testData: {},
            // testColumn: [
            //  { prop: 'name', label: '试卷名称', width: '' },
            //  { prop: 'subject', label: '试卷分类', width: '' },
            //  { prop: 'create_time', label: '组卷时间', width: '' },
            // ],
            // 关联资源
            resourceVisible: false,
            resourceType: '',
            keyword: '',
            resourceData: {},
            resourceColumn: [
                { prop: 'name', label: '资源名称', width: '' },
                { prop: 'u_name', label: '用户名', width: 160 },
                { prop: 'category', label: '资源分类', width: 160 },
                { prop: 'fileType', label: '资源类型', width: 80 },
                { prop: 'create_time', label: '上传时间', width: 140 }
            ],
            resourceChecked: [],
            page: 1,
            size: 10,
            types: ['全部', '文档', '日志', '图片', '压缩文件', '音频文件', '视频', '应用程序', '其他'],
            // 本地上传
            uploadOptions: {
                target: this.BASE_URL + '/api/resource/res_upload',
                testChunks: false,
                headers: { Authorization: `Bearer ` + this.$g.access_token }
            },
            uploadNumber: 0,
            uploadLimitMax: 100000,
            statusText: {
                success: '上传成功',
                error: '上传出错',
                uploading: '正在上传...',
                paused: '暂停',
                waiting: '等待上传'
            },
            errorFlag: false //验证输入框是否为空
        };
    },
    created() {},
    mounted() {},
    computed: {
        // 合并关联视频/关联资源的数据
        relate_data() {
            let video = this.changeArr(this.videoChecked, 'video', 'video_name');
            // let test = this.changeArr(this.testChecked,'test','name');
            let resource = this.changeArr(this.resourceChecked, 'resource', 'name');
            return [...video, ...resource];
        }
    },
    watch: {
        // 判断当前是第几章，把关联的table数据放到relate_data字段里面
        relate_data: {
            handler(newVal, oldVal) {
                let a = this.tabsData[this.tabIndex - 1].relate_data;
                let arr = a.concat(newVal);
                let list = []
                for (var i = 0; i < arr.length; i++) {
                    if (arr[i].tab == this.tabIndex) {
                        list.push(arr[i])
                    }
                }
                let data = this.filterArr(list, 'res_id');

                if (this.$route.name === 'album-add') {
                    this.tabsData[this.tabIndex - 1].relate_data = data
                } else {
                    let a = [...this.tabsData[this.tabIndex - 1].relate_data, ...data]
                    this.tabsData[this.tabIndex - 1].relate_data = this.filterArr(a, 'res_id');
                }



            },
            immediate: true
        },
        tabsData: {
            handler(newVal, oldVal) {
                this.$emit('input', newVal);
            },
            deep: true
        },
        //3.文件上传完成提交数据
        uploadNumber: {
            handler(newVal, oldVal) {
                if (this.$refs.uploaderRes) {
                    let fileNumber = this.$refs.uploaderRes.fileList.length;
                    if (newVal === fileNumber) {
                        this.postData();
                    }
                }
            },
            immediate: true
        }
    },
    methods: {
        // 数组去重 arr：数组;key:根据数组中为key的键名去重
        filterArr(arr, key) {
            let hash = {};
            return arr.reduce((ss, item) => {
                hash[item[key]] ? '' : (hash[item[key]] = true && ss.push(item));
                return ss;
            }, []);
        },
        // 根据table中checkbox勾上的数据，转成提交后台需要的格式[{name:"",res_id:"",type:""}]
        changeArr(arr, type, name) {
            let data = [];
            arr.map(item => {
                const obj = {};
                obj.name = item[`${name}`];
                obj.res_id = item.id;
                obj.type = type;
                obj.tab = item.tab;
                data.push(obj);

            });
            return data;
        },
        // 新增或者删除tab
        editTab(targetName, action) {
            if (action === 'add') {
                let newTabName = this.tabsData.length + 1 + '';
                this.tabsData.push({
                    title: `第${newTabName}章`,
                    inx: newTabName,
                    name: '',
                    profile: '',
                    relate_data: []
                });
                this.tabIndex = newTabName;
            } else if (action === 'remove') {
                if (this.tabsData.length <= 1) {
                    this.$message.warning('已经是最后一章了，不能删除');
                    return;
                }
                let tabs = this.tabsData;
                tabs = tabs.filter(tab => tab.inx !== targetName); //删除项
                this.tabsData = tabs.map((tab, inx) => {
                    //重设标题、索引
                    const newInx = ++inx + '';
                    tab.title = `第${newInx}章`;
                    tab.inx = newInx;
                    return tab;
                });
                //重设高亮状态
                let a = this.tabIndex;
                let b = targetName < a || (targetName == a && targetName != '1') ? a - 1 : a;
                this.tabIndex = b.toString();
            }
        },
        //   删除关联文件
        delresource(scope) {
            this.$confirm('此操作将删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    customClass: 'confirm-them'
                })
                .then(() => {
                    let inx = scope.$index;
                    let files = this.$refs.uploaderRes.uploader.fileList;
                    files = files.filter(x => scope.row.upload_id && scope.row.upload_id != x.id);
                    this.$refs.uploaderRes.uploader.fileList = files;
                    this.$refs.uploaderRes.uploader.files = files;
                    this.tabsData[this.tabIndex - 1].relate_data.splice(inx, 1);
                })
                .catch(() => {});
        },
        //   关联视频/关联试卷/关联资源 按钮点击事件
        connect(type) {
            this.$refs[`${type}Table`].visible = true;
            switch (type) {
                case 'video':
                    this.searchVideo();
                    break;
                case 'test':
                    this.searchTest();
                    break;
                case 'resource':
                    this.searchResource();
                    break;
                default:
                    break;
            }
        },
        //   获取视频数据
        searchVideo() {
            let params = {
                keyword: this.keyword,
                page_index: this.page,
                page_size: this.size,
                status: 1,
                authority: 1,
                type: this.videoType
            };
            let success = data => {
                this.videoData = data.data;
            };
            this.$ajax.get('api/video/video_list', {
                params,
                func: { success: success }
            });
        },
        // // 获取试卷数据
        // searchTest() {
        //  let params = {
        //         keyword: this.keyword,
        //         page_index: this.page,
        //         page_size: this.size,
        //         status: 1,
        //         authonity: 1,
        //  };
        //  let success = data => {
        //      this.testData = data.data;
        //  };
        //  this.$ajax.get('api/test/test', {
        //      params,
        //      func: { success: success }
        //  });
        // },
        // 获取资源数据
        searchResource() {
            let params = {
                authonity: 1,
                keyword: this.keyword,
                file_type: this.resourceType,
                data_type: 2,
                not_in_file_type: 2,
                page: this.page,
                size: this.size
            };
            let success = data => {
                let res = data.data;
                if (res.data && res.data.length > 0) {
                    res.data.map((item, index) => {
                        item.fileType = this.types[item.file_type];
                    });
                    this.resourceData = res;
                }
            };
            this.$ajax.get('api/resource/resource', {
                params,
                func: { success: success }
            });
        },
        // 本地上传相关
        fileSuccessRes(rootFile, file, message, chunk) {
            let mess = JSON.parse(message);
            outer: for (var i = this.tabsData.length - 1; i >= 0; i--) {
                if (this.tabsData[i].relate_data.length > 0) {
                    for (var j = this.tabsData[i].relate_data.length - 1; j >= 0; j--) {
                        if (!is_empty(this.tabsData[i].relate_data[j].upload_id) && this.tabsData[i].relate_data[j].upload_id === file.id) {
                            this.tabsData[i].relate_data[j].path = mess.data.file_path;
                            this.tabsData[i].relate_data[j].postfix = mess.data.post_fix;
                            this.uploadNumber++;
                            continue outer;
                        }
                    }
                }
            }
        },

        fileFailRes(rootFile, file, message, chunk) {
            var mess = JSON.parse(message);
            if (parseInt(mess.error) === 401 && this.uploadRetryTimes > 0) {
                let callbcak = data => {
                    this.uploadRetryTimes--;
                    this.$refs.uploaderRes.uploader.retry(file);
                };
                this.get_access_token(callbcak);
            } else {
                this.$message.error(mess.msg);
            }
        },
        fileSubmitRes(files, fileList, event) {
            for (var i = 0; i < fileList.length; i++) {
                var ext = fileList[i].name
                    .split('.')
                    .pop()
                    .toLocaleLowerCase();
                if (ext === 'mpg') {
                    this.$message.warning('不允许上传的文件格式');
                    this.$refs.uploaderRes.uploader.removeFile(fileList[i]);
                } else if (fileList[i].size === 0) {
                    this.$refs.uploaderRes.uploader.removeFile(fileList[i]);
                    this.$message.error('上传文件大小不能小于0');
                } else if (fileList[0].size > this.uploadLimitMax * 1024 * 1024 && this.uploadLimitMax > 0) {
                    this.$message.warning('只允许上传' + this.uploadLimitMax + 'M以内的文件');
                    this.$refs.uploaderRes.uploader.removeFile(fileList[i]);
                } else {
                    this.tabsData[this.tabIndex - 1].relate_data.push({
                        res_inx: this.tabsData[this.tabIndex - 1].relate_data.length,
                        upload_id: fileList[i].id,
                        name: fileList[i].name,
                        type: 'resource',
                        path: '',
                        postfix: '',
                        res_id: null
                    });
                }
            }
        },
        fileRemovedRes(file) {
            // console.log(file)
        },
        fileUploadRes() {
            this.$refs.uploaderRes.uploader.resume();
        },
        //课程目录
        // 1.验证名称input框是否为空
        // 2.上传功能如有文件,则上传
        // 3.如果本地上传功能 的文件都上传完毕，执行父组件里的post请求，再上传数据，否则直接上传数据
        validateCatalog() {
            //1.验证输入框是否为空
            this.errorFlag = true;
            let inxData = [];
            this.tabsData.forEach((x, inx) => {
                if (x.name === '') {
                    inxData.push(inx + 1);
                }
            });
            if (inxData.length > 0) {
                // const emptyInx = inxData.join(',');
                // const tip = `课程目录：第${emptyInx}章，阶段/单元名称不能为空`;
                // this.$message.error(tip);
                // return
            }
            // 2.上传文件
            const files = this.$refs.uploaderRes.uploader.fileList;
            if (files.length > 0) {
                this.fileUploadRes();
            } else {
                this.postData();
            }
        }
    }
};

</script>
<style lang="scss">
.album-catalog {
    .content {
        background-color: #e0e0e0;
        padding: 20px;
    }
    .validate-input {
        .el-input__inner {
            border: 1px solid #f56c6c;
        }
        p {
            display: inline;
            color: #f56c6c;
            font-size: 12px;
        }
    }
    .relate-table {
        width: 100%;
        .el-icon-delete {
            display: inline-block;
            padding: 5px 10px;
            font-size: 14px;
            cursor: pointer;
        }
    }
    .btns-row {
        padding-top: 20px;
        .el-button {
            margin-right: 10px;
        }
        .uploader {
            display: inline-block;
        }
        .uploader-btn {
            margin-left: 40px;
            background-color: transparent;
            border: none;
        }
    }
    .table-row {
        padding-top: 20px;
        .el-pagination {
            margin-top: 20px;
        }
    }
}

</style>
